﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;

namespace Faz.SideWinderSC.Client
{
    /// <summary>
    /// Provides the convertion between a single <see cref="Key"/> and an array of <see cref="Key"/>.
    /// </summary>
    public class KeyConverter : IValueConverter
    {
        /// <summary>
        /// Converts a single value into an array.
        /// </summary>
        /// <param name="value">The value to convert.</param>
        /// <param name="targetType">The expected type for the result.</param>
        /// <param name="parameter">The parameter is not used.</param>
        /// <param name="culture">The parameter is not used.</param>
        /// <returns>
        /// An array of <see cref="Key"/> containing the the single key represented by <paramref name="value"/>;
        /// or <c>null</c> if <paramref name="value"/> is <c>null</c>;
        /// or <see cref="DependencyProperty.UnsetValue"/> if the parameters are not correct.
        /// </returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType == typeof(Key[]))
            {
                Key? key = value as Key?;
                if (key.HasValue)
                {
                    return new Key[] { key.Value };
                }
                else
                {
                    return null;
                }
            }

            return DependencyProperty.UnsetValue;
        }

        /// <summary>
        /// Converts an array into a single value.
        /// </summary>
        /// <param name="value">The value to convert.</param>
        /// <param name="targetType">The expected type for the result.</param>
        /// <param name="parameter">The parameter is not used.</param>
        /// <param name="culture">The parameter is not used.</param>
        /// <returns>
        /// The first <see cref="Key"/> of the array represented by <paramref name="value"/>;
        /// or <c>null</c> if <paramref name="value"/> is <c>null</c> or empty;
        /// or <see cref="DependencyProperty.UnsetValue"/> if the parameters are not correct.
        /// </returns>
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType == typeof(Key?))
            {
                Key[] keys = value as Key[];
                if (keys == null || keys.Length == 0)
                {
                    return null;
                }
                else
                {
                    return keys[0];
                }
            }

            return DependencyProperty.UnsetValue;
        }
    }
}
